package com.kcht.np.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kcht.np.common.jwt.JwtUser;
import com.kcht.np.entity.SysUser;
import com.kcht.np.common.exception.ParameterException;
import com.kcht.np.common.exception.UserExistsException;
import com.kcht.np.service.SysUserService;
import com.kcht.np.util.JsonResult;
import com.kcht.np.util.JsonUtils;
import com.kcht.np.vo.page.QueryParameter;
import com.kcht.np.vo.UserRelatedRoleVo;
import com.kcht.np.vo.user.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户管理 控制器
 * </p>
 *
 * @Package: com.kcht.np.mp.controller
 * @Description: 用户管理 控制器
 * @Author: liuqi
 * @CreateDate: 2020/3/31 11:43
 */

@Slf4j
@Api(tags = "[ 权限管理 ] 用户管理")
@SuppressWarnings("all")
@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    protected SysUserService userService;


    /*--------------查询操作--------------------*/






    /*拥有管理用户权限可执行的查询操作*/
    @ApiOperation(value = "[管理员]查询指定用户", notes = "通过用户唯一标识查询用户基本信息")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('pre_user')")
    public JsonResult<SysUser> queryUserById(@PathVariable("id") Long uid) {
        return JsonResult.success(userService.getById(uid));
    }

    @ApiOperation(value = "[管理员]查看所有用户", notes = "查看所有用户的基本信息")
    @GetMapping("/all")
    @PreAuthorize("hasAuthority('pre_user')")
    public JsonResult<List<SysUser>> querySysUsers() {

        return JsonResult.success(userService.list());
    }

    @ApiOperation(value = "[管理员]分页查询用户", notes = "分页查询用户详情")
    @GetMapping("/info/page")
    @PreAuthorize("hasAuthority('pre_user')")
    public JsonResult pagingQueryUsers(QueryParameter parameter,BindingResult br) {
        IPage<SysUserVo> page = userService.pagingQueryUsers(parameter);
        return JsonResult.success(page.getPages(),page.getTotal(),page.getRecords());
    }


    /*所有用户可执行的查询操作*/
    @ApiOperation(value = "[普通用户]查询个人", notes = "用户获取个人信息，登录系统即可查看")
    @GetMapping("/info")
    @PreAuthorize("isAuthenticated()")
    public JsonResult<UserVo> userQueryPersonalInfo() {
        return JsonResult.success(userService.userQueryPersonalInfo());
    }

    /*-----------------修改操作-------------------*/
    /*拥有管理用户权限可执行的修改操作*/
    @ApiOperation(value = "[管理员]修改指定用户拥有角色")
    @PostMapping("/update/roles")
    @PreAuthorize("isAuthenticated()")
    public JsonResult updateRolePermissions(@RequestBody @Validated UserRelatedRoleVo data, BindingResult br) {
        try{
            userService.resetUserRoles(data.getUid(), data.getRoles());
            return JsonResult.success();
        }catch (ParameterException e){
            return JsonResult.result(400,e.getMessage());
        }
    }

    @ApiOperation(value = "[管理员]修改指定用户所属部门")
    @PutMapping("/dept")
    @PreAuthorize("hasAuthority('pre_perm:update')")
    public JsonResult<SysUser> updateUserDept(Long uid,Long deptId) {
        try{
            userService.updateDept(uid,deptId);
            return JsonResult.success();
        }catch (ParameterException e){
           return JsonResult.result(400,e.getMessage());
        }
    }

    @ApiOperation(value = "[管理员]修改指定用户", notes = "可修改指定用户的基本信息")
    @PutMapping("")
    @PreAuthorize("hasAuthority('pre_perm:update')")
    public JsonResult<SysUser> userUpdate(@RequestBody @Validated ManagerCanModifyInfo user, BindingResult br) {
        try{
            userService.updateById(user);
            return JsonResult.success();
        }catch (ParameterException e){
            return JsonResult.result(400,e.getMessage());
        }
    }

    /*所有用户可执行的修改操作*/
    @ApiOperation(value = "[普通用户]修改", notes = "用户修改自身信息")
    @PutMapping("/user")
    @PreAuthorize("isAuthenticated()")
    public JsonResult<SysUser> userUpdateSelf(@RequestBody @Validated UserCanModifyInfo entity, BindingResult br) {
        try{
            userService.userUpdateSelf(entity);
            return JsonResult.success();
        }catch (ParameterException e){
            return JsonResult.result(400,e.getMessage());
        }
    }


    /*---------------创建操作-----------------*/
    @ApiOperation(value = "[管理员]创建用户", notes = "创建用户")
    @PostMapping("")
    @PreAuthorize("hasAuthority('pre_user:create')")
    public JsonResult<SysUser> create(@RequestBody @Validated UserCanCreateInfo entity, BindingResult br) {
        try{
            userService.save(entity);
            return JsonResult.success();
        }catch (UserExistsException e){
            return JsonResult.result(400,e.getMessage());
        }catch (ParameterException e){
            return JsonResult.result(400,e.getMessage());
        }
    }


    /*--------------删除操作-----------------*/
    @ApiOperation(value = "[管理员]删除用户", notes = "删除用户实体")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('pre_user:delete')")
    public JsonResult<String> delete(@PathVariable("id")Long id) {
        try{
            userService.deleteUser(id);
            return JsonResult.success();
        }catch (ParameterException e){
            return JsonResult.result(400,e.getMessage());
        }
    }
}
